<template>
  <div class="student-info-form">
    <div style="margin-bottom: 15px">
      <el-button type="primary" @click="exportExcel"
        >导出学员信息Excel</el-button
      >
    </div>

    <el-table
      v-loading="loading"
      :data="tableData"
      border
      :row-class-name="tableRowClassName"
      :cell-style="cellStyle"
    >
      <el-table-column type="index" width="60" label="序号" />
      <el-table-column label="状态" prop="name" width="55" align="center">
        <template #default="scope">
          <el-tooltip
            class="box-item"
            v-if="scope.row.userState == 0"
            effect="dark"
            :content="`停课日期 ${scope.row.suspensionClassDate}`"
            placement="top"
          >
            <div style="color: #8530f5">停课</div>
          </el-tooltip>
          <div class="status-icon" v-else-if="scope.row.userState == 2">
            <img
              src="https://shdiditazi.oss-cn-shanghai.aliyuncs.com/image/6ec5b77ded30e5ff51a211dd703a097f.png"
              alt=""
            />
          </div>
          <div v-else class="status-icon">
            <img src="@/assets/images/checkIcon.png" alt="" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="姓名" prop="baseInfo.name" width="100" />
      <el-table-column label="性别" prop="name" width="80">
        <template #default="scope">
          {{ getGenderByIdCard(scope.row.baseInfo.identityCard) }}
        </template>
      </el-table-column>
      <el-table-column label="报送人社" prop="name" width="80">
        <template #default="scope">
          <div v-if="scope.row.isSubmit" class="button" style="color: #67c23a">
            是
          </div>
          <div v-else class="button" style="color: #f56c6c">否</div>
        </template>
      </el-table-column>
      <el-table-column prop="baseInfo.mobile" label="联系方式" width="150" />
      <el-table-column label="地址">
        <template #default="scope">
          <el-input
            v-model="scope.row.address"
            placeholder="请输入学员地址"
            @change="setData(scope.row, 'address')"
          />
        </template>
      </el-table-column>
      <el-table-column prop="price" label="备注" align="center">
        <template #default="scope">
          <el-input
            v-model="scope.row.remark"
            placeholder="请输入备注"
            @change="setData(scope.row, 'remark')"
          />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
const instance = getCurrentInstance();
const { proxy } = getCurrentInstance();
let props = defineProps(["info", "type"]);

let tableData = ref([]);
let list = [];
let templateUrl = "";
let loading = ref(false);

// onMounted(() => {
//   getInfo();
//   getTemplateUrl();
// });

const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: User;
  rowIndex: number;
}) => {
  if (row.userState == 0) {
    return "warning-row";
  }
  return "";
};

function cellStyle({ row, column, rowIndex, columnIndex }) {
  if ([6, 7].includes(columnIndex)) {
    return { "background-color": "rgba(252, 235, 156, 0.2)" };
  }
}

async function setData(row, key) {
  let data = {
    classId: props.info._id,
    userId: row.userId,
    [key]: row[key],
  };
  await proxy.$apis.classReport({ type: "B3-update", data });
  proxy.$utils.showToast("修改成功");
  getInfo();
}

function getGenderByIdCard(idCard) {
  if (!idCard || idCard.length !== 18) {
    throw new Error("Invalid ID card number");
  }
  const sexCode = idCard.charAt(16);
  const gender = parseInt(sexCode, 10) % 2 === 0 ? "女" : "男";
  return gender;
}

async function getInfo() {
  try {
    loading.value = true;
    let list = [];
    let resp = await counter.studentInfo(props.info._id);
    resp.forEach((element) => {
      if (element.userState != 2) {
        list.push(element);
      }
    });
    tableData.value = list;
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

async function getTemplateUrl() {
  templateUrl = await proxy.$apis.fileTemplate({
    data: { type: props.type },
    type: "downLoad",
  });
}

async function exportWord() {
  if (!templateUrl) return proxy.$utils.showToast("请先上传模板", 0);

  let ret = await proxy.$apis.classDocExport({
    templateURL: templateUrl,
    data: { tableData: counter.studentExportParams(tableData.value) },
    fileName: "学员信息表.docx",
  });
  window.location.href = ret;
}

function downLoadTemplate() {
  window.location.href = templateUrl;
}

async function exportExcel() {
  let data = [];
  for (let index = 0; index < tableData.value.length; index++) {
    const element = tableData.value[index];
    data.push({
      姓名: element.baseInfo.name,
      性别: getGenderByIdCard(element.baseInfo.identityCard),
      报送人社: element.isSubmit ? "是" : "否",
      联系方式: element.baseInfo.mobile,
      地址: element.address,
      备注: element.remark,
    });
  }
  let cols = []; //设置表头样式
  tableData.value.forEach((element) => {
    cols.push({ wch: 20 });
  });
  let query = { jsonData: data, cols };
  await proxy.$utils.exportToExcel(query, "学员信息表");
}

watch(
  () => [props.info, props.type],
  (newValue, oldValue) => {
    if (newValue) {
      getTemplateUrl();
      getInfo();
    }
  },
  { deep: true, immediate: true }
);

defineExpose({
  exportWord,
  downLoadTemplate,
});
</script>

<style lang="scss">
.el-table .warning-row {
  --el-table-tr-bg-color: #f5f7fa;
}
</style>

<style lang="scss" scope>
.status-icon {
  width: 15px;
  height: 15px;
  margin: auto;
  img {
    width: 100%;
    display: block;
  }
}
</style>
